package task04.enteties;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * User: jeetrainee
 * Date: 10/28/13
 * Time: 9:35 PM
 * To change this template use File | Settings | File Templates.
 */
public class CustomFileUtil {
    private String filePath;

    private FileInputStream inputStream;
    private FileOutputStream outputStream;

    private BufferedOutputStream bufferedOutputStream;
    private BufferedInputStream bufferedInputStream;

    public CustomFileUtil(String filePath) {
        this.filePath = filePath;
    }

    public void writeObjectToFile(String text) throws IOException {
        byte[] userBytes = text.getBytes();
        outputStream = new FileOutputStream(filePath);

        outputStream.write(userBytes);
        outputStream.close();
    }

    public String readObjectFromFile() throws IOException {
        inputStream = new FileInputStream(filePath);
        byte[] byteArray = new byte[(int) new File(filePath).length()];

        inputStream.read(byteArray);
        inputStream.close();

        return new String(byteArray);
    }

    public void writeObjectToFileBuffered(String text) throws IOException {
        byte[] userBytes = text.getBytes();
        bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(filePath));

        bufferedOutputStream.write(userBytes);
        bufferedOutputStream.close();
    }

    public String readObjectFromFileBuffered() throws IOException {
        byte[] byteArray = new byte[(int) new File(filePath).length()];
        bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath));

        bufferedInputStream.read(byteArray);
        bufferedInputStream.close();

        return new String(byteArray);
    }

    public float getWriteDiffTime(String text) throws IOException {
        float result = 0;
        long firstTime = 0;
        long secondTime = 0;

        firstTime = System.nanoTime();
        writeObjectToFileBuffered(text);
        firstTime = System.nanoTime() - firstTime;

        secondTime = System.nanoTime();
        writeObjectToFile(text);
        secondTime = System.nanoTime() - secondTime;

        result = (float) ((float) firstTime / (float) secondTime);

        return result;
    }

    public float getReadDiffTime(String text) throws IOException {
        float result = 0;
        long firstTime = 0;
        long secondTime = 0;

        firstTime = System.nanoTime();
        text = readObjectFromFileBuffered();
        firstTime = System.nanoTime() - firstTime;

        secondTime = System.nanoTime();
        text = readObjectFromFile();
        secondTime = System.nanoTime() - secondTime;

        result = (float) ((float) firstTime / (float) secondTime);

        return result;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
}
